package com.heima.behavior.service.Impl;


import com.alibaba.fastjson.JSON;
import com.heima.behavior.interceptor.AppTokenInterceptor;
import com.heima.behavior.service.ApLikeBehaviorService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;

import com.heima.model.behavvior.dtos.LikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApLikeBehaviorServiceImpl implements ApLikeBehaviorService {

    @Autowired
    private CacheService cacheService;

    /**
     * 用户存储喜欢的数据
     * 存储到redis
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        //1 检查参数
        if (dto == null || dto.getArticleId() == null || checkParam(dto)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2 检查用户是否登录
        ApUser apUser = AppThreadLocalUtil.getUser();
        if(apUser == null){
            // 无登录无法点赞
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3 点赞 保存数据到redis 存到hash表中 key = LIKE_BEHAVIOR + 文章的id   hashKey = 用户id  value =  dto的JSON序列化
        if(dto.getOperation() == 0){ //0 代表点赞行为
            //查询redis中是否已经存在数据
            Object object = cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + dto.getArticleId().toString(), apUser.getId().toString());
            if (object != null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"已点赞");
            }

            //保存当前key
            log.info("用户点赞：保存当前key：{}，{}，{}",dto.getArticleId(),apUser.getId(),dto);
            cacheService.hPut(BehaviorConstants.LIKE_BEHAVIOR,dto.getArticleId().toString(),JSON.toJSONString(dto));
        }else {
            //取消点赞，删除当前key
            log.info("用户取消点赞：删除当前key：{}，{}，{}",dto.getArticleId(),apUser.getId(),dto);
            cacheService.hDelete(BehaviorConstants.LIKE_BEHAVIOR,dto.getArticleId().toString());
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 检查参数
     *
     * @return
     */
    private boolean checkParam(LikesBehaviorDto dto) {
        if (dto.getType() > 2 || dto.getType() < 0 || dto.getOperation() > 1 || dto.getOperation() < 0) {
            return true;
        }
        return false;
    }

}
